import React, { useState, useEffect, useRef } from "react";
import { Menu, Modal, Button, Checkbox, message, Divider } from "antd";
import {
  AppstoreOutlined,
  LeftOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import "../style/indexlist.css";
import IndexList from "./IndexList";
import pinyin from "pinyin";
import axios from "axios";
import "../mock/orgtree";
import "../mock/org3145";
import "../mock/org3146";
import "../mock/org3147";
import "../mock/user6363";
/**
 * 
 *  menus   栏目列表
    changeJoin    修改外部参会人列表
    users   已选中的参会人
 */

const WOrglist = (props) => {
  /**机构路径，当前层级*/
  // var orgArr = [""];
  // var orgIndex = 0;
  /**对话框显示 */
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [Modaltitle, setModaltitle] = useState();
  const [orgArr, setOrgArr] = useState([]);
  const [orgIndex, setOrgIndex] = useState(0);
  const [isAllSelectVisible, setIsAllSelectVisible] = useState("none");

  const [menusSrc, setMenusSrc] = useState();

  /**弹出对话框 */
  const showModal = () => {
    setIsModalVisible(true);
  };

  const showAllSelect = (val) => {
    setIsAllSelectVisible(val);
  };

  /**确认对画框 */
  const handleOk = () => {
    setIsModalVisible(false);
    var checkedId = [];
    var checked = document.querySelectorAll(
      "#content a.cell input[type='checkbox']:checked"
    );

    checked.forEach((i) => {
      checkedId = [...checkedId, i.id];
    });
    // console.log(checkedId);
    props.changeJoin(checkedId);
    handleCancel();
  };

  /**关闭对话框 ,重置数据*/
  const handleCancel = async () => {
    setOrgIndex(1);
    setOrgArr(["_教职工+N"]);
    setModaltitle("教职工");
    putMenu("", false);
    setIsModalVisible(false);
    setIsAllSelectVisible("none");
  };
  /**返回上一级 */
  const handleBack = async () => {
    if (orgIndex >= 1) {
      let orgId = orgArr[orgIndex - 1].slice(
        0,
        orgArr[orgIndex - 1].indexOf("_")
      );
      let orgName = orgArr[orgIndex - 1].slice(
        orgArr[orgIndex - 1].indexOf("_") + 1,
        orgArr[orgIndex - 1].length - 2
      );
      await setOrgIndex(orgIndex - 1);
      await setOrgArr(orgArr.slice(0, orgIndex));
      await setModaltitle(orgName);

      // console.log(orgIndex - 1);
      console.log(orgArr);
      console.log(orgId);
      await putMenu(orgId);
    } else {
      message.info("已经在最上级了");
    }
  };

  const checkedAll = (e) => {
    console.log(e.target.checked);
    var checked = document.querySelectorAll(
      "#content a.cell input[type='checkbox']"
    );
    if (e.target.checked) {
      checked.forEach((i) => {
        i.checked = true;
      });
    } else {
      checked.forEach((i) => {
        i.checked = false;
      });
    }
  };

  /**创建子结构 */
  const changeMenu = (val) => {
    console.log(orgIndex);
    console.log(orgArr);
    return (
      <Menu
        mode="inline"
        // style={{ width: 256 }}
        onClick={getChildMenu}
      >
        {
          // console.log(val);
          val.map((v) => {
            // console.log(v.id);
            // console.log(v.children);
            let isLeaf = v.state === "closed" ? "N" : "Y";
            //是否为末端节点
            return (
              <Menu.Item
                key={v.id + "_" + v.text + "+" + isLeaf}
                icon={<AppstoreOutlined />}
              >
                <span className="nav-text">{v.text}</span>
              </Menu.Item>
            );
          })
        }
      </Menu>
    );
  };

  const putMenu = async (id, isOpen) => {
    /**渲染子机构 */
    await axios
      .get("orgTree.rst?id=" + id)
      .then(async (res) => {
        let response = res.data;
        // response = response.data;
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          // console.log(res);
          if (isOpen) {
            /**点击菜单跳转子机构 */
            let orgId = isOpen.key.slice(0, isOpen.key.indexOf("_"));
            let orgName = isOpen.key.slice(
              isOpen.key.indexOf("_") + 1,
              isOpen.key.length - 2
            );

            let isLeaf = isOpen.key.slice(isOpen.key.length - 1);
            // console.log(orgId + "_" + orgName + "+" + isLeaf);
            /**留存历史节点 */
            /**层级 */
            await setOrgIndex(orgIndex + 1);
            /**路径数组 */
            await setOrgArr([...orgArr, orgId + "_" + orgName + "+" + isLeaf]);
            /**对话框title */
            await setModaltitle(orgName);
          }
          setMenusSrc(await changeMenu(res));
          /**清空并关闭添加表单 */
        } else {
          message.error("机构数据请求失败");
        }
      })
      .catch((error) => {
        message.error("机构数据请求失败");
      });

    // console.log(orgIndex);
    // console.log(orgIndex);
    // console.log(orgArr);
  };

  /**渲染人员列表 */
  const putIndexList = (data) => {
    /**数据分组排序 */
    var dataSource = transferToSectionsData(data);

    /*渲染页面 */
    setMenusSrc(<IndexList data={dataSource.data} />);
  };

  const transferToSectionsData = (dataList) => {
    console.log(dataList);
    //获取联系人列表
    let sections = [],
      letterArr = [];
    // 右侧字母栏数据处理
    dataList.forEach((item, index, arr) => {
      let itemTemp = pinyin(item.EMPNAME.substring(0, 1), {
        style: pinyin.STYLE_FIRST_LETTER,
      })[0][0].toUpperCase();
      letterArr.push(itemTemp);
    });
    letterArr = [...new Set(letterArr)].sort();
    // this.setState({ letterArr: letterArr });
    console.log({ letterArr: letterArr });

    // 分组数据处理
    letterArr.forEach((item, index, arr) => {
      sections.push({
        title: item,
        items: [],
      });
    });

    dataList.forEach((item1, index1, arr1) => {
      let listItem = item1;
      sections.forEach((item2, index2, arr2) => {
        let firstName = listItem.EMPNAME.substring(0, 1);
        let firstLetter = pinyin(firstName, {
          style: pinyin.STYLE_FIRST_LETTER,
        })[0][0].toUpperCase();
        let pinyinStrArr = pinyin(listItem.EMPNAME, {
          style: pinyin.STYLE_NORMAL,
        });
        // console.log("pinyinStr", pinyinStrArr);
        if (item2.title === firstLetter) {
          item2.items.push({
            firstName: firstName,
            name: listItem.EMPNAME,
            id: listItem.EMPID,
            signature: listItem.SIGNATURE,
            photo: listItem.PHOTO,
          });
        }
      });
    });
    return { data: sections };
  };

  const putPeople = (id) => {
    /**请求人员列表 */
    axios
      .get("searchUsers.rst?orgId=" + id)
      .then(async (res) => {
        let response = res.data;
        // response = response.data;
        if (response.resultCode === 0) {
          let res = response.result.data;
          console.log(res);
          /**渲染人员列表 */
          putIndexList(res);

          /**清空并关闭添加表单 */
        } else {
          message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        console.log(error);
        message.error("人员数据请求失败");
      });
  };

  const getChildMenu = (e) => {
    /**点击菜单跳转子机构 */
    let orgId = e.key.slice(0, e.key.indexOf("_"));
    let isLeaf = e.key.slice(e.key.length - 1);
    // console.log(isLeaf);
    // let orgName = e.key.slice(e.key.indexOf("_") + 1);
    console.log(isLeaf);
    if (isLeaf === "N") {
      //有子节点
      /**渲染子机构 */
      putMenu(orgId, e);
      /**全选按钮 */
      showAllSelect("none");
    } else {
      //无子节点
      /**渲染机构人员 */
      putPeople(orgId);
      /**全选按钮 */
      showAllSelect("block");
    }
  };

  useEffect(() => {
    getChildMenu({ key: "_教职工+N" });

    /**操作DOM */
    // var span = document.getElementById("Wcheckbox");
    // checkboxLabel.current
  }, [props.menus]);

  return (
    <>
      <Button type="primary" onClick={showModal}>
        +
      </Button>
      <Modal
        title={Modaltitle}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        className="WOrglist"
        destroyOnClose
        closable={false}
        style={{
          bottom: 0,
          top: 0,
          margin: "0px",
          padding: "0px",
          maxWidth: "100vw",
          position: "fixed",
        }}
        footer={
          <>
            <a class="cell" style={{ display: isAllSelectVisible }}>
              <input
                id="all"
                class="select"
                type="checkbox"
                onChange={checkedAll}
              />
              <label for="all">全选</label>
            </a>
            <Button type="primary" onClick={handleOk}>
              保存
            </Button>
          </>
        }
      >
        <LeftOutlined
          onClick={handleBack}
          className="handle-btn "
          style={{ color: "#8c8c8c", fontSize: "20px" }}
        />
        <CloseOutlined
          onClick={handleCancel}
          className="handle-btn handle-btn2"
          style={{ color: "#8c8c8c", fontSize: "20px" }}
        />

        {/* <Menu
          mode="inline"
          // style={{ width: 256 }}
          onClick={getChildMenu}
        >
          {menusSrc}
        </Menu> */}
        {menusSrc}
      </Modal>
    </>
  );
};

export default WOrglist;
